GO写的 RESful API 1.简单的GO Web 创建请求api http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { _, _ = fmt.Fprintln(writer, "Android服务后台,%q", html.EscapeString(request.URL.Path)) }) 监听端口
GO写的 RESful API
1.简单的GO Web
- 创建请求api
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
_, _ = fmt.Fprintln(writer, "Android服务后台,%q", html.EscapeString(request.URL.Path))
})
- 监听端口
log.Fatal(http.ListenAndServe(":8080",router))
- 解释
-
http.HandleFun(path,fun(write,request))
创建handle处理函数 -
fmt.Fprintln
输出到网页 -
http.ListenAndServer(url,nil)
监听端口
- 结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Gca1nBYi-1583212882838)(C:\Users\Primer4\Documents\学习笔记\1583152716793.png)]
2.使用mux路由
- 导包
"github.com/gorilla/mux"
import - 步骤
- 创建router路由
router:=mux.NewRouter().StrictSlash(true)
- 添加handler处理函数
router.HandleFunc("/index",IndexHandle)
- 创建handler函数
func IndexHandle(writer http.ResponseWriter, request *http.Request) {
_, _ = fmt.Fprintln(writer, "mux路由器")
}
- 监听服务器
http.ListenAndServe(":8080",router)
3.添加更多路由
- 当前handler继续添加
router.HandleFunc("/name",NameHandle)
- 添加可选的{}
router.HandleFunc("/name/{id}",NameByIdHandle)
func NameByIdHandle(writer http.ResponseWriter, request *http.Request) {
vars:=mux.Vars(request)
val:=vars["id"]
_, _ = fmt.Fprintln(writer, vars)
_, _ = fmt.Fprintln(writer, val)
}
4.创建模型
- 创建模型
json标签,指定json key的值,避免冲突
//user结构体
type User struct {
Id int `json:"id"`
Name string `json:"name"`
CreateTime string `json:"create_time"`
}
//别名
type Users []User
- 添加handle处理函数
func UserHandle(writer http.ResponseWriter, request *http.Request) {
user:=modle.User{
Id:24,
Name:"Git",
CreateTime:time.Unix(time.Now().Unix(),0).Format("2006-01-02 03:04:05 PM"),
}
jsonStr := json.NewEncoder(writer).Encode(user)
_, _ = fmt.Fprintln(writer, jsonStr)
}
5.重构代码 & 添加网络日志
- 步骤
- 日志
func MyLog(inner http.Handler,msg string)http.Handler{
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
msg,
time.Since(start),
)
})
}
- 五步走
// 1.创建自定义路由
type CustomRoute struct {
Name string
Method string
Path string
HandlerFunc http.HandlerFunc
}
type Routes []CustomRoute
// 2.路由数组管理
var routers = Routes{
CustomRoute{
"IndexHandle",
"GET",
"/index",
IndexHandle,
},
CustomRoute{
"NameHandle",
"GET",
"/name",
NameHandle,
},
CustomRoute{
"NameByIdHandle",
"GET",
"/name/{id}",
NameByIdHandle,
},
CustomRoute{
"UserHandle",
"GET",
"/users",
UserHandle,
},
}
// 3.根据集合创建 路由
func NewRouter()* mux.Router{
route := mux.NewRouter().StrictSlash(true)
var handle http.Handler
for _,r := range routers{
// 4.添加日志
handle = r.HandlerFunc
handle = mylog.MyLog(handle,r.Name)
route.Methods(r.Method).Path(r.Path).Name(r.Name).Handler(handle)
}
return route
}
func main() {
// 5.创建路由
routers:=NewRouter()
log.Fatal(http.ListenAndServe(":8080",routers))
}
6.部署运行程序
- 后台运行
chmod 777
./程序名 &
遇到的Linux问题
- 杀死后台进程
kill -9 pid
- 查看端口占用情况
lsof -i:8080
- 后台运行
nohub ./程序名 &
<关闭终端也会继续运行> - 查看所有正在运行的Linux进程信息
ps -aux
Android遇到问题
- 传输过来的数据是数组,自己接受的是对象
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
解决
接受的返回值改为数组
7.基于Android Retrofit网络请求example
public interface UserService {
//http://xxx:8081/users
@GET("users")
Call<List<UserDao>> getUsers();
}
Retrofit userRetrogit;
userRetrogit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://xxxxxx:8081/")
.build();
userService = userRetrogit.create(UserService.class);
Call<List<UserDao>> users = userService.getUsers();
users.enqueue(new Callback<List<UserDao>>() {
@Override
public void onResponse(Call<List<UserDao>> call, Response<List<UserDao>> response) {
Log.d(TAG, "onResponse: "+response.body().size());
List<UserDao> body = response.body();
for(UserDao i:body){
Log.d(TAG, "onResponse: "+i.toString());
}
}
@Override
public void onFailure(Call<List<UserDao>> call, Throwable t) {
Log.d(TAG, "onFailure: 失败users");
Log.d(TAG, "onFailure: 失败原因\n"+t.toString());
}
});
结果输出
【感谢龙石为本站提供数据中台建设http://www.longshidata.com/pages/government.html】