text golang restful api

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text golang restful api相关的知识,希望对你有一定的参考价值。

package main

import (
	"log"
	"net/http"

	"./userservice"
	"github.com/emicklei/go-restful"
)

func main() {
	restful.Add(userservice.New())
	log.Fatal(http.ListenAndServe(":8080", nil))
}
=============== ./userservice =========


package userservice

import (
	"net/http"
	"fmt"
	"github.com/emicklei/go-restful"
)

type User struct {
	Id, Name string
}

func New() *restful.WebService {
	service := new(restful.WebService)
	service.
		Path("/users").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	service.Route(service.GET("/{user-id}").To(FindUser))
	service.Route(service.POST("").To(UpdateUser))
	service.Route(service.PUT("/{user-id}").To(CreateUser))
	service.Route(service.DELETE("/{user-id}").To(RemoveUser))

	return service
}

func FindUser(request *restful.Request, response *restful.Response) {
	id := request.PathParameter("user-id")
	// here you would fetch user from some persistence system
	usr := &User{Id: id, Name: "pugar"}
	response.WriteEntity(usr)
	fmt
}

func UpdateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(&usr)
	// here you would update the user with some persistence system
	if err == nil {
		response.WriteEntity(usr)
	} else {
		response.WriteError(http.StatusInternalServerError, err)
	}
}

func CreateUser(request *restful.Request, response *restful.Response) {
	usr := User{Id: request.PathParameter("user-id")}
	err := request.ReadEntity(&usr)
	// here you would create the user with some persistence system
	if err == nil {
		response.WriteEntity(usr)
	} else {
		response.WriteError(http.StatusInternalServerError, err)
	}
}

func RemoveUser(request *restful.Request, response *restful.Response) {
	// here you would delete the user from some persistence system
}

以上是关于text golang restful api的主要内容,如果未能解决你的问题,请参考以下文章

golang rest api example

API(几乎)与GoLang的RESTFul变量响应

使用 GoLang 后端反应 JS Rest API 安全性

golang Go中的基本RESTful API - https://medium.com/@etiennerouzeaud/how-to-create-a-basic-restful-api-i

Golang REST API - 从经过验证和解码的令牌传递信息

GraphQL 用例:使用 Golang 和 PostgreSQL 构建一个博客引擎 API