当前位置: 首页 > 工具软件 > go-restful > 使用案例 >

go-restful项目demo搭建(1)

颛孙高义
2023-12-01
  1. mkdir test_project
    
  2. cd test_project
    
  3. go mod init
    
  4. export GOPROXY="https://goproxy.io"
    
  5. export GO111MODULE=on
    
  6. go mod download
    
  7. 修改main.go
package main
import(
    "fmt"
    "github.com/emicklei/go-restful"
    "net/http"
)

func main() {
    fmt.Printf("runing.....\n")
    ws := new(restful.WebService)
    ws.Path("/hello")
    ws.Route(ws.GET("/").To(ping).Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON))
    container := restful.NewContainer()
    container.Add(ws)

    http.ListenAndServe(":8080", container)

}
type Resp struct{
    Code int
    Msg string
    //data interface{}
}

func ping(request *restful.Request, response *restful.Response) {
    fmt.Printf("pong.....\n")
    data := Resp{Code:0, Msg:"test"}
    response.WriteEntity(data)
}
  1. go mod tidy #add missing and remove unused modules
    
  2. go run main.go
    
  3. 访问localhost:8080/hello
 类似资料: