2017-01-22 15 views
1

我想做一个API来处理具有路径的请求,如 http:\\localhost:8080\todo\something但我需要使用自定义服务器。[去]自定义服务器来处理具体路径的请求

这是我写的一段代码。

package main 

import (
     "net/http" 
     "fmt" 
     "io" 
     "time" 
    ) 


func myHandler(w http.ResponseWriter, req *http.Request){ 
    io.WriteString(w, "hello, world!\n") 
} 


func main() { 

    //Custom http server 
    s := &http.Server{ 
     Addr:   ":8080", 
     Handler:  http.HandlerFunc(myHandler), 
     ReadTimeout: 10 * time.Second, 
     WriteTimeout: 10 * time.Second, 
     MaxHeaderBytes: 1 << 20, 
    } 

    err := s.ListenAndServe() 
    if err != nil { 
     fmt.Printf("Server failed: ", err.Error()) 
    } 
} 

post

我的灵感来自处理所有接受该请求这样http:localhost:8080\abchttp:localhost:8080\abc等 如何使其只处理请求的路径匹配给定制服务器路径。

回答

1

如果您想要使用不同的URL路径,您必须创建一些mux,您可以创建一个,使用go提供的默认多路复用器或使用第三方多路复用器,如gorilla

以下代码是使用所提供的标准http库制作的。

func myHandler(w http.ResponseWriter, req *http.Request){ 
    io.WriteString(w, "hello, world!\n") 
} 

func main() { 
    mux := http.NewServeMux() 
    mux.HandleFunc("/todo/something", func(w http.ResponseWriter, r *http.Request) { 
     w.Write([]byte("Response")) 
    }) 

    s := &http.Server{ 
     Addr:   ":8080", 
     Handler:  mux, 
     ReadTimeout: 10 * time.Second, 
     WriteTimeout: 10 * time.Second, 
     MaxHeaderBytes: 1 << 20, 
    } 
    s.ListenAndServe() 
} 
相关问题