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 ...
随机推荐
- java 23种设计模式 深入浅出
以下内容只作为对自己对知识进行总结,如有引用他人文章会在文段末尾表明出处: Java的23种设计模式 23种设计模式总共可以分为三大类,进行不定期更新总结,将逐步展开介绍自己对设计模式的理解,多多指教 ...
- BZOJ2741 FOTILE模拟赛L(分块+可持久化trie)
显然做个前缀和之后变成询问区间内两个数异或最大值. 一种暴力做法是建好可持久化trie后直接枚举其中一个数查询,复杂度O(nmlogv). 观察到数据范围很微妙.考虑瞎分块. 设f[i][j]为第i个 ...
- 【BZOJ1434】[ZJOI2009]染色游戏(博弈论)
[BZOJ1434][ZJOI2009]染色游戏(博弈论) 题面 BZOJ 洛谷 题解 翻硬币的游戏我似乎原来在博客里面提到过,对于这类问题,当前局面的\(SG\)函数就是所有反面朝上的硬币单一存在时 ...
- 洛谷 P2245 星际导航 解题报告
P2245 星际导航 题目描述 sideman做好了回到Gliese 星球的硬件准备,但是sideman的导航系统还没有完全设计好.为了方便起见,我们可以认为宇宙是一张有N 个顶点和M 条边的带权无向 ...
- CF1110E Magic Stones(构造题)
这场CF怎么这么多构造题…… 题目链接:CF原网 洛谷 题目大意:给定两个长度为 $n$ 的序列 $c$ 和 $t$.每次我们可以对 $c_i(2\le i<n)$ 进行一次操作,也就是把 $c ...
- CRT && exCRT模板
CRT从各种方面上都吊打exCRT啊...... 短,好理解... 考虑构造bi使得bi % pi = ai,bi % pj = 0.然后全加起来就行了. 显然bi的构造就是ai * (P/pi) * ...
- MySQL日志功能详解
MySQL日志功能详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.查询日志 它是用来保存所有跟查询相关的日志,这种日志类型默认是关闭状态的,因为MySQL的用户有很多,如果 ...
- AngularJS总结
因为最近想学习一下ionic框架,了解到ionic是基于AngularJS语法,并且通过SASS构建应用程序,之前自己一直用Vue框架,还有Less,刚刚好趁此机会,学习一下AngularJS与SAS ...
- JavaScript编写风格指南 (一)
//参考<编写可维护的Javascript> 一:缩进// 第一行的层级由4个空格组成,避免使用制表符tab进行缩进 //好的写法if (true) { doSomething() ...
- 20155212 2016-2017-2 《Java程序设计》第6周学习总结
20155212 2016-2017-2 <Java程序设计>第6周学习总结 教材学习内容总结 Chapter10 输入串流为java.io.InputStream,输出串流为java.i ...