Simple Web API Server in Golang (1)
To be an better Gopher, get your hands dirty. Topcoder offered a serials of challenges for learning Golang.
In this blog, I tried to implement "Go Learning Challenge - Simple Web-API Server"[1].
What's used in this challenge ? Following aspects and packages will be covered in this challenge
- How to create a HTTP server: net/http
- How to create routers (handlers for different URLs): regex + url
- How to write HTTP responses: net/http
- How to load JSON config: json + io/ioutil
- How to parse URL query string: url
- How to encode data in sha256/base64: sha256/base64 + strings
- How to write tests in Golang: testing
- How to parse command line arguments: flag
- How to log: log
Configuration File example:
[
{
"domain": "topcoder.com",
"users": [
{
"username": "takumi",
"password": "ilovego"
},
{
"username": "teru",
"password": "ilovejava"
},
{
"username": "toshi",
"password": "iloveapex"
}
]
},
{
"domain": "appirio.com",
"users": [
{
"username": "jun",
"password": "ilovetopcoder"
},
{
"username": "narinder",
"password": "ilovesamurai"
},
{
"username": "chris",
"password": "ilovesushi"
}
]
}
]
config.go
package SimpleWebAPIServer import (
"io/ioutil"
"encoding/json"
"errors"
) type User struct {
UserName string `json:"username"`
Password string `json:"password"`
} type Domain struct {
Name string `json:"domain"`
Users UserList `json:"users"`
} type DomainWarehouse []Domain
type UserList []User func ReadConfig(fn string) (DomainWarehouse, error) {
data, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
//fmt.Println(string(data)) var m DomainWarehouse
json.Unmarshal(data, &m)
return m, nil
} func (dw DomainWarehouse) GetDomain(name string) (*Domain, error) {
for _, domain := range dw {
if domain.Name == name {
return &domain, nil
}
}
return nil, errors.New("Failed to find domain")
} func (ul UserList) GetUser(username string) (*User, error) {
for _, user := range ul {
if user.UserName == username {
return &user, nil
}
}
return nil, errors.New("Failed to find user")
}
tests for config.go
package SimpleWebAPIServer import (
"testing"
"fmt"
) func TestReadConfig(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
if dw == nil || len(dw) != {
t.Error("Failed to unmarshal json objects")
} if dw[].Name != "topcoder.com" || len(dw[].Users) != {
t.Error("Incorrect value")
}
} func TestGetDomain(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
domain, err := dw.GetDomain("topcoder.com")
if err != nil {
fmt.Println(err)
t.Error("Failed to get domain")
}
if domain.Name != "topcoder.com" || len(domain.Users) != {
t.Error("Incorrect value")
}
} func TestGetUser(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
domain, err := dw.GetDomain("topcoder.com")
if err != nil {
fmt.Println(err)
t.Error("Failed to get domain")
}
if domain.Name != "topcoder.com" || len(domain.Users) != {
t.Error("Incorrect value")
} ul := domain.Users
u, err := ul.GetUser("takumi")
if err != nil {
t.Error("Failed to get user")
}
if u.UserName != "takumi" || u.Password != "ilovego" {
t.Error("Invalid user values")
}
}
After implementing this simple web api server, I got better understanding of Golang syntax and Web API stuffs. For more Web API server challenges, go to [3] about OAuth2.
[1] topcoder : http://www.topcoder.com/challenge-details/30046011/?type=develop&noncache=true
[2] git : https://coding.net/u/huys03/p/SimpleWebAPIServer/git
[3] next challenge: http://www.topcoder.com/challenge-details/30046224/?type=develop
Simple Web API Server in Golang (1)的更多相关文章
- Simple Web API Server in Golang (2)
In this challenge, I tried to implement a simple OAuth2 server basing on Simple Web API Server in [1 ...
- 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API
原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...
- 【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)
HTTP is not just for serving up web pages. It's also a powerful platform for building APIs that expo ...
- [转]【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)
本文转自:https://www.cnblogs.com/inday/p/6288707.html HTTP is not just for serving up web pages. It’s al ...
- Running Web API using Docker and Kubernetes
Context As companies are continuously seeking ways to become more Agile and embracing DevOps culture ...
- [转]Enabling CRUD Operations in ASP.NET Web API 1
本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/creating-a-web-api-that ...
- Asp.Net MVC 4 Web API 中的安全认证-使用OAuth
各种语言实现的oauth认证: http://oauth.net/code/ 上一篇文章介绍了如何使用基本的http认证来实现asp.net web api的跨平台安全认证. 这里说明一个如何使用oa ...
- Creating A Simple Web Server With Golang
原文:https://tutorialedge.net/post/golang/creating-simple-web-server-with-golang/ -------------------- ...
- [转]Getting started with ASP.NET Web API OData in 3 simple steps
本文转自:https://blogs.msdn.microsoft.com/webdev/2013/01/29/getting-started-with-asp-net-web-api-odata-i ...
随机推荐
- MongoDB-管道与聚合(3)
分组:$group() db.集合.aggregate( {$group: {_id:'$分组字段名', 显示字段:{$统计函数: '$统计字段'}}}, ) -- 统计男生 ...
- Cuba项目从远程Git仓库下载步骤
Cuba Studio 从Git远程仓库里下载代码,并且可以使用IDEA打开,需要注意的地方: 1.使用Git Gui克隆代码 也可以使用IDEA本身集成的Git下载,但是要保证:下载了项目以后,不能 ...
- MT【103】二阶递推找规律
评:如果直接找$a_n$的二阶递推式:$a_{n+2}-2\sqrt{2}a_{n+1}-a_n=0$有根号,不利于估计尾数.
- 【BZOJ1083】[SCOI2005]繁忙的都市(最小生成树)
[BZOJ1083][SCOI2005]繁忙的都市(最小生成树) 题面 BZOJ 洛谷 题解 模板题. #include<iostream> #include<cstdio> ...
- 【转】Example of using the --info linker option
5.3 Example of using the --info linker option This is an example of the output generated by the --in ...
- MHN蜜罐的安装部署
MHN(Modern Honey Network),是一个用于管理和收集蜜罐数据的中心服务器.通过MHN,可以实现快速部署多种类型的蜜罐并且通过web可视化界面显示蜜罐收集的数据,目前支持的蜜罐类型有 ...
- MySQL的COUNT()函数理解
MySQL的COUNT()函数理解 标签(空格分隔): MySQL5.7 COUNT()函数 探讨 写在前面的话 细心的朋友会在平时工作和学习中,可以看到MySQL的COUNT()函数有多种不同的参数 ...
- bzoj 1824: [JSOI2010]下棋问题
考虑每次新放一个棋子会产生多少新的矩形,以及减掉多少旧的矩形. 用第$i$个点的坐标把坐标轴分成4个象限. 显然第一问的答案用四个单调栈就能解决. 而且第二问每个矩形的两个端点一定在1,3或2,4象限 ...
- ByteBuffer: 当由一个byte[]来生成一个固定不变的ByteBuffer时,使用ByteBuffer.wrap(byte[]);
StringBuilder sb = new StringBuilder(1024); //向sb中写入900个左右的随机字符内容 for(int j=1; j< 50;j++) { sb.ap ...
- ctrl+E 快速显示当前打开的编辑列表
ctrl+E 快速显示当前打开的编辑列表