package main
import (
"encoding/json"
"fmt"
"log"
)
type User struct {
ID int `json:"id"`
Score int `json:"score"`
}
func main() {
fileBytes := []byte(`[
{
"id":1,
"score": 335
},
{
"id":2,
"score": 123
},
{
"id":3,
"score": 321
}
]`)
var users []User
err := json.Unmarshal(fileBytes, &users)
if err != nil {
log.Fatalf("Failed to unmarshal: %s", err)
}
fmt.Printf("%#v\n", users)
newUser := User{
ID: 4,
Score: 1488,
}
users = addIfNotExist(users, newUser)
fmt.Printf("%#v\n", users)
// Дальше Marshal и сохранение в файле
}
func addIfNotExist(users []User, user User) []User {
for _, u := range users {
if u.ID == user.ID {
return users
}
}
return append(users, user)
}
package main
import (
"fmt"
"encoding/json"
"log"
)
func main() {
bodyBytes := []byte(`{"ok":true,"result":[{"update_id":715296593,
"message":{"message_id":5,"from":{"id":362268798,"is_bot":false,"first_name":"\u041a\u043e\u0442\ud83d\udd25","username":".....","language_code":"ru"},"chat":{"id":362268798,"first_name":"\u041a\u043e\u0442\ud83d\udd25","username":"....","type":"private"},"date":1604728384,"text":"/start","entities":[{"offset":0,"length":6,"type":"bot_command"}]}}]}`)
var data map[string]interface{}
err := json.Unmarshal(bodyBytes, &data)
if err != nil {
log.Fatal(err)
}
result, ok := data["result"].([]interface{})
if !ok {
log.Fatal("Failed to type-cast result")
}
firstResult, ok := result[0].(map[string]interface{})
if !ok {
log.Fatal("Failed to type-cast first result")
}
message, ok := firstResult["message"].(map[string]interface{})
if !ok {
log.Fatal("Failed to type-cast message")
}
chat, ok := message["chat"].(map[string]interface{})
if !ok {
log.Fatal("Failed to type-cast chat")
}
fmt.Println("id =", chat["id"])
fmt.Println("type = ", chat["type"])
fmt.Println("username = ", chat["username"])
fmt.Println("first_name = ", chat["first_name"])
}
package main
import (
"fmt"
"encoding/json"
"log"
)
type Response struct {
Results []Result `json:"result"`
}
type Result struct {
Message Message `json:"message"`
}
type Message struct {
Chat Chat `json:"chat"`
}
type Chat struct {
ID int `json:"id"`
FirstName string `json:"first_name"`
UserName string `json:"username"`
Type string `json:"type"`
}
func main() {
bodyBytes := []byte(`{"ok":true,"result":[{"update_id":715296593,
"message":{"message_id":5,"from":{"id":362268798,"is_bot":false,"first_name":"\u041a\u043e\u0442\ud83d\udd25","username":".....","language_code":"ru"},"chat":{"id":362268798,"first_name":"\u041a\u043e\u0442\ud83d\udd25","username":"....","type":"private"},"date":1604728384,"text":"/start","entities":[{"offset":0,"length":6,"type":"bot_command"}]}}]}`)
var response Response
err := json.Unmarshal(bodyBytes, &response)
if err != nil {
log.Fatal(err)
}
fmt.Println("id =", response.Results[0].Message.Chat.ID)
fmt.Println("type = ", response.Results[0].Message.Chat.Type)
fmt.Println("username = ", response.Results[0].Message.Chat.UserName)
fmt.Println("first_name = ", response.Results[0].Message.Chat.FirstName)
}
package main
import (
"fmt"
)
func main() {
funcWithCounter1 := funcWithCounter()
fmt.Println(funcWithCounter1())
fmt.Println(funcWithCounter1())
fmt.Println(funcWithCounter1())
funcWithCounter2 := funcWithCounter()
fmt.Println(funcWithCounter2())
fmt.Println(funcWithCounter2())
}
func funcWithCounter() func() int {
var counter int
return func() int {
// тут полезная работа
counter++
return counter
}
}
c := sync.NewCond(&sync.Mutex{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
c.L.Lock()
defer c.L.Unlock()
c.Wait()
fmt.Println("I'm created")
}()
time.Sleep(1 * time.Second)
c.Signal()
wg.Wait()
func (p *Product) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
v := struct {
Price string `xml:"Price"`
}{}
d.DecodeElement(&v, &start)
p.Price = strings.Trim(v.Price, " ")
return nil
}
FileServer
, так как указан корневой уровень. Сделайте, например, для файлов /public
, тогда api будет работать. Еще нужно будет этот префикс удалить с помощью http.StripPrefix
fs := http.StripPrefix("/public", http.FileServer(http.Dir("public")))
r.PathPrefix("/public").Handler(fs)
jsonSource := `{"access_token_XXXXXX":"533bacf01e11f55b536a565b57531ac114461ae8736d6506a3", "expires_in":0}`
var raw map[string]interface{}
err := json.Unmarshal([]byte(jsonSource), &raw)
if err != nil {
log.Fatal(err)
}
for key, val := range raw {
fmt.Printf("%s: %v\n", key, val)
}
package "handlers"
import "database/sql"
type User struct {
db *sql.DB
}
func NewUser(db *sql.DB) *User {
return &User{db: db}
}
func (u *User) Add(w http.ResponseWriter, r *http.Request) {
// u.db - доступ к db
}
func (u *User) GetInfo(w http.ResponseWriter, r *http.Request) {
// u.db - доступ к db
}
package main
import "handlers"
func main(){
//...
//установление соединения к postgres
DB, err = ConnectToDB()
userHandler := handlers.NewUser(DB)
http.HandleFunc("/adduser/", userHandler.Add)
http.HandleFunc("/getinfo/", userHandler.GetInfo)
http.ListenAndServe(":8080", nil)
}
// Подготовка исходного слайса
sourceSize := 9600
source := make([]int, sourceSize)
for i := 0; i < sourceSize; i++ {
source[i] = i+1
}
// Разбиение слайса
chunkSize := 1000
result := make([][]int, 0)
var first, last int
for i := 0; i < len(source) / chunkSize + 1; i++ {
first = i * chunkSize
last = i * chunkSize + chunkSize
if last > len(source) {
last = len(source)
}
if first == last {
break
}
result = append(result, source[first:last])
}
// Вывод результата
for _, res := range result {
fmt.Println(res)
}
package main
import (
"fmt"
"sort"
)
func main() {
var arr = []int{1, 3, 2}
sort.SliceStable(arr, func(i, j int) bool {
return arr[i] > arr[j] // здесь поправил
})
for _, val := range arr {
fmt.Println(val)
}
}