go语言使用github.com/gorilla/mux发布REST service

一个使用github.com/gorilla/mux实现REST API Service的例子,主要内容包括:

  1. GET/POST方法,如何接收path参数,query参数,以及POST body参数
  2. 如何设置返回状态码,如何返回JSON数据body
  3. 验证Handler函数是同步的还是异步的,单线程的还是多线程的

GET方法

发布一个GET REST API,接收client请求,并解析URL带的查询参数,最后返回JSON数据。
main.go

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

var (
  hostname   string
  port       int
)

/* register command line options */
func init() {
    flag.StringVar(&hostname, "hostname", "0.0.0.0", "The hostname or IP on which the REST server will listen")
    flag.IntVar(&port, "port", 8080, "The port on which the REST server will listen")
}

func main() {
    flag.Parse()
    var address = fmt.Sprintf("%s:%d", hostname, port)
    log.Println("REST service listening on", address)

    // register router
    router := mux.NewRouter().StrictSlash(true)
    router.
        HandleFunc("/api/service/get", MyGetHandler).
        Methods("GET")

    // start server listening
    err := http.ListenAndServe(address, router)
    if err != nil {
        log.Fatalln("ListenAndServe err:", err)
    }

    log.Println("Server end")
}

handle.go

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "github.com/gorilla/mux"
)

func MyGetHandler(w http.ResponseWriter, r *http.Request) {
  // parse query parameter
  vals := r.URL.Query()
  param, _ := vals["servicename"]  // get query parameters

  // composite response body
  var res = map[string]string{"result":"succ", "name":param[0]}
  response, _ := json.Marshal(res)
  w.Header().Set("Content-Type", "application/json")
  w.Write(response)
}

运行

# on server
$ go build && ./main 
2017/09/16 15:04:23 REST service listening on 0.0.0.0:8080

# on client
$ curl -X GET http://localhost:8080/api/service/get?servicename=myname
{"name":"myname","result":"succ"}

POST方法

这个例子client发送POST消息,并使用path变量,同时附带JSON格式body消息体,server端解析body内容,并返回JSON信息。
这里只给出POST相关代码,其他框架的代码请参考GET方法
main.go

  // register router
  router := mux.NewRouter().StrictSlash(true)
  router.
    HandleFunc("/api/service/get", MyGetHandler).
    Methods("GET")
  router.
    HandleFunc("/api/service/{servicename}/post", MyPostHandler).
    Methods("POST")

handle.go

func MyPostHandler(w http.ResponseWriter, r *http.Request) {
  // parse path variable
  vars := mux.Vars(r)
  servicename := vars["servicename"]

  // parse JSON body
  var req map[string]interface{}
  body, _ := ioutil.ReadAll(r.Body)
  json.Unmarshal(body, &req)
  servicetype := req["servicetype"].(string)

  // composite response body
  var res = map[string]string{"result":"succ", "name":servicename, "type":servicetype}
  response, _ := json.Marshal(res)
  w.Header().Set("Content-Type", "application/json")
  w.Write(response)
}

运行

$ curl -X POST -d '{"servicetype":"mytype"}' http://localhost:8080/api/service/myservice/post
{"name":"myservice","result":"succ","type":"mytype"}

HTTP 返回值

上面例子返回的都是200 OK,如何可以根据服务运行状态返回不同的状态码呢?
以GET方法为例
handler.go

func MyGetHandler(w http.ResponseWriter, r *http.Request) {
  var res map[string]string = make(map[string]string)
  var status = http.StatusOK

  vals := r.URL.Query()
  param, ok := vals["name"]
  if (!ok) {
    res["result"] = "fail"
    res["error"] = "required parameter name is missing"
    status = http.StatusBadRequest
  } else {
    res["result"] = "succ"
    res["name"] = param[0]
    status = http.StatusOK
  }

  response, _ := json.Marshal(res)
  w.WriteHeader(status)
  w.Header().Set("Content-Type", "application/json")
  w.Write(response)
}

运行结果

  • 第一个请求,返回200 OK
$ curl -v -X GET http://localhost:8080/api/service/get?name=myname
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/service/get?name=myname HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Sat, 16 Sep 2017 07:41:38 GMT
< Content-Length: 33
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact
{"name":"myname","result":"succ"}
  • 第二个请求,返回400 Bad Request
$ curl -v -X GET http://localhost:8080/api/service/get
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/service/get HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 400 Bad Request
< Date: Sat, 16 Sep 2017 07:41:42 GMT
< Content-Length: 62
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact
{"error":"required parameter name is missing","result":"fail"} 

Handler函数是同步的还是异步的

在前面的例子中我们看到了,w http.ResponseWriter可以用来设置返回信息的Status值,Header信息,以及Body内容,如果我们什么也不做,会出什么结果呢,验证
handler.go

func MyGetHandler(w http.ResponseWriter, r *http.Request) {
  // do nothing
}

测试

$ curl -v -X GET http://localhost:8080/api/service/get?name=myname
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/service/get?name=myname HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Sat, 16 Sep 2017 07:50:18 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact

可以看到client正常的收到了200 OK的返回码。

再做一个例子,让Handler sleep一段时间

func MyGetHandler(w http.ResponseWriter, r *http.Request) {
  time.Sleep(5*time.Second);
}

客户端

$ time curl -v -X GET http://localhost:8080/api/service/get?name=myname
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/service/get?name=myname HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Sat, 16 Sep 2017 07:56:12 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact

real    0m5.081s
user    0m0.005s
sys 0m0.009s

可以看到client在5秒之后正常的返回了,那么我们的结论是Handler函数返回的时候,client也就收到了server的返回;所以handler是一个同步调用函数。然后紧接着我们自然想到另一个问题。

Handler函数是单线程的还是多线程的

第一个问题,不同的handler能否同时进来
handler.go

func MyGetHandler(w http.ResponseWriter, r *http.Request) {
  log.Println("entry of MyGetHandler")
  time.Sleep(10*time.Second);
  log.Println("exit of MyGetHandler")
}

func MyPostHandler(w http.ResponseWriter, r *http.Request) {
  log.Println("entry of MyPostHandler")
  time.Sleep(2*time.Second);
  log.Println("exit of MyPostHandler")
}

测试
打开三个终端,一个运行server,一个调用MyGetHander,另一个调用 MyPostHandler。
终端1: server

2017/09/16 16:12:32 entry of MyGetHandler
2017/09/16 16:12:35 entry of MyPostHandler
2017/09/16 16:12:37 exit of MyPostHandler
2017/09/16 16:12:42 exit of MyGetHandler

终端2: MyGetHandler

$ date && time curl -X GET http://localhost:8080/api/service/get?name=myname
Sat Sep 16 16:12:32 CST 2017

real    0m10.020s
user    0m0.006s
sys 0m0.006s

终端2: MyPostHandler

$ date && time curl -X POST -d '{"servicetype":"mytype"}' http://localhost:8080/api/service/myservice/post
Sat Sep 16 16:12:35 CST 2017

real    0m2.017s
user    0m0.005s
sys 0m0.005s

通过比较时间戳,我们可以发现GetHandler已经在处理了,此时PostHandler刚进来,然后PostHander退出后,GetHander再退出,因此不同的Handler的执行方式是多线程的,多个请求可以冲入。

第2个问题,同一个handler能否同时进来
handler.go

func MyGetHandler(w http.ResponseWriter, r *http.Request) {
  log.Println("entry of MyGetHandler")

  vals := r.URL.Query()
  param, ok := vals["name"]
  if (ok) {
    log.Println("name=", param[0])
  }

  time.Sleep(5*time.Second);
  log.Println("exit of MyGetHandler")
}

测试
和第一个问题一样采用三个终端
终端1: server

2017/09/16 16:18:17 entry of MyGetHandler
2017/09/16 16:18:17 name= myname1
2017/09/16 16:18:19 entry of MyGetHandler
2017/09/16 16:18:19 name= myname2
2017/09/16 16:18:22 exit of MyGetHandler
2017/09/16 16:18:24 exit of MyGetHandler

终端2: MyGetHandler

$ date && time curl -X GET http://localhost:8080/api/service/get?name=myname1
Sat Sep 16 16:18:17 CST 2017

real    0m5.032s
user    0m0.005s
sys 0m0.009s

终端2: MyPostHandler

$ date && time curl -X GET http://localhost:8080/api/service/get?name=myname2
Sat Sep 16 16:18:19 CST 2017

real    0m5.021s
user    0m0.006s
sys 0m0.006s

结论是同一个Handler函数也是可以重入的。

    原文作者:CodingCode
    原文地址: https://www.jianshu.com/p/5973d1999f5d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞