通过例子学GO语言Web开发之移植网易云音乐API项目

网易云音乐API

在github中网易云音乐系列的开源项目中最多star应该是NeteaseCloudMusicApi许多好玩的网易云音乐项目都是基于这个项目,今天将带领大家熟悉这个优秀的项目同时移植到GO语言中,通过移植进一步熟悉go语言以及gin框架。

项目地址:

  go版本:https://github.com/Jackkakaya/NeteaseCloudMusicGoApi

  node原版:https://github.com/Binaryify/NeteaseCloudMusicApi

进入node版github主页

go版本主页

 发现node版本的星星真多


node版本因为比较成熟里有doc/test等文档以及测试目录,go中的是抽取所有核心后的。app.go是项目的入口可以从这里开始阅读。因项目逻辑类似,为了学习go语言这里仅分析

go版本。

func InitRouter() *gin.Engine {
    //gin.SetMode(gin.ReleaseMode)
    var musicObain models.MusicObain
    store := persistence.NewInMemoryStore(time.Second)
    r := gin.New()
    // 注册中间件
    r.Use(gin.Logger())
    r.Use(gin.Recovery())
    r.Use(RequestModifyMiddleware)
    files, err := ioutil.ReadDir(ModelPath)
    if err != nil {
        log.Fatalln(err)
    }
    filter := map[string]bool{
        "music_obtain.go": true,
    }
    // 遍历models文件夹,将文件名形成路由
    // 例如文件名:album_sublist.go是将path为album/sublist的请求router path
    // 请求到album_sublist.go 中的AlbumSublist方法处理
    for _, file := range files {
        if filename := file.Name(); filter[filename] == false {
            filename = strings.TrimSuffix(filename, ".go")
            path := fmt.Sprintf("/%v", strings.ReplaceAll(filename, "_", "/"))
            method := strings.ReplaceAll(strings.Title(strings.ReplaceAll(filename, "_", " ")), " ", "")
       // 接受任意请求方法 r.Any(path, cache.CachePage(store,
2*time.Minute, func(context *gin.Context) { query := map[string]interface{}{} data, _ := ioutil.ReadAll(context.Request.Body) _ = json.Unmarshal(data, &query) CookieParseMiddleware(context, &query) for key, val := range context.Request.URL.Query() { query[key] = val[0] } for key, val := range context.Request.PostForm { query[key] = val }
          // 通过放射调用指定包中的结构体下的方法 respRaw :
= reflect.ValueOf(&musicObain).MethodByName(method).Call([]reflect.Value{reflect.ValueOf(query)}) resp := respRaw[0].Interface().(map[string]interface{}) for _, val := range resp["cookie"].([]string) { context.Writer.Header().Add("Set-Cookie", val) } context.JSON(200, resp) })) } } return r }

 项目入口核心函数InitRouter,自动化形成路由,形成路由的规则如下:

  请求demo:

    localhost:8080/login/cellphone?phone=xxxx&password=xxxx

    那么就会将请求打到login_cellphone.go中的LoginCellphone方法处理。

  

  请求核心:pkg/request/request.go

    这个包中实现了所有请求的封装,建议熟读此包

    业务处理:models/*

  业务逻辑举例:

package models

import "github.com/Jackkakaya/NeteaseCloudMusicGoApi/pkg/request"

func (m *MusicObain) ActivateInitProfile(query map[string]interface{}) map[string]interface{} {
	data := map[string]interface{}{
		"nickname": query["nickname"],
	}
	options := map[string]interface{}{
		"crypto": "eapi",
		"cookie": query["cookie"],
		"proxy":  query["proxy"],
		"url":    "/api/activate/initProfile",
	}
	return request.CreateRequest(
		"POST", "http://music.163.com/eapi/activate/initProfile",
		data,
		options)
}

  业务逻辑这里,主要是处理好参数,调用pkg/request下的CreateRequest方法去请求。

 

总结

  整个项目最核心的就是gin的路由处理函数InitRouter,自动化形成路由同时加入中间件处理,此外就是pkg中的request下的CreateRequest是对所有请求的封装

   models下是所有业务逻辑每个业务逻辑都是调用request/CreateRequest来请求。

最后

  项目地址:https://github.com/Jackkakaya/NeteaseCloudMusicGoApi

  欢迎下载学习。建议跟着源码学习。欢迎star!!

 

  

  

  

猜你喜欢

转载自www.cnblogs.com/jake9402/p/12525290.html