package main
import (
"fmt"
)
type HandlersMap map[string]func(string) string
func (hm HandlersMap) RegisterHandler(path string, handler func(string) string) {
hm[path] = handler
}
func main() {
m := make(HandlersMap, 0)
m.RegisterHandler("1", myFunc1)
m.RegisterHandler("2", myFunc2)
handler1 := m["1"]
handler2 := m["2"]
fmt.Println(handler1("handler 1 output"))
fmt.Println(handler2("handler 2 output"))
}
func myFunc1(s string) string {
return fmt.Sprintf("MyFunc1: %s", s)
}
func myFunc2(s string) string {
return fmt.Sprintf("MyFunc2: %s", s)
}
$ go run main.go
MyFunc1: handler 1 output
MyFunc2: handler 2 output
func handleRequest(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 1024)
b := bufio.NewReader(conn)
for {
line, err := b.ReadBytes('\n')
if err != nil { // for example EOF
break
}
buf = append(buf, line...)
}
fmt.Print(string(buf))
}
func handleRequest(conn net.Conn) {
message := make([]byte, 1024)
_, error := conn.Read(message)
if error != nil {
fmt.Println(error)
os.Exit(1)
}
fmt.Println(string(message))
conn.Close()
}
Мы выбираем номер элемент под номером индексом 3 (т.е число 4) и прибавляем к этому индексу к примеру 2. Как сделать, чтобы вывелось число 1(т.е список заканчивается проходит число 5 и "коретка" идет в начало списка и выводит число 1)
>>> import itertools
>>> idx = 5
>>> for i, j in enumerate(itertools.cycle([1,2,3,4,5])):
... if i == idx:
... print(j)
... break
... else:
... continue
...
1
https://domain.name/data.json?searchtext=Запрос+На+Кириллице
package main
import (
"fmt"
"net/url"
)
func main() {
q := "Запрос+На+Кириллице"
u := "https://domain.name/data.json"
fmt.Println(u + "?searchtext=" + url.QueryEscape(q))
}
$ go run main.go
https://domain.name/data.json?searchtext=%D0%97%D0%B0%D0%BF%D1%80%D0%BE%D1%81%2B%D0%9D%D0%B0%2B%D0%9A%D0%B8%D1%80%D0%B8%D0%BB%D0%BB%D0%B8%D1%86%D0%B5
go get golang.org/x/net/idna
package main
import (
"fmt"
"golang.org/x/net/idna"
)
var p *idna.Profile
func main() {
p = idna.New()
fmt.Println(p.ToASCII("россия.рф"))
}
$ go run main.go
xn--h1alffa9f.xn--p1ai <nil>
type MyType ext_api.Data
func (m *MyType) PrintDataEx() {...}
type MyStruct struct {
*ext_api.Data
}
func (m *MyStruct) Method() {...}
m := &MyStruct{...}
m.Method()
Don’t create a session per request. Most likely you need a session per application which performs all requests altogether.
import asyncio
import aiohttp
async def call_url(url, session):
print('Starting {}'.format(url))
async with session.get(url) as response:
response = await session.get(url)
data = await response.text()
print('{}: {} bytes: {}'.format(url, len(data), data))
return data
async def run(urls):
async with aiohttp.ClientSession() as session:
futures = [call_url(url, session) for url in urls]
result = await asyncio.gather(*futures)
return result
if __name__ == '__main__':
urls = ['http://www.google.com',
'http://www.yandex.ru', 'http://www.python.org']
ioloop = asyncio.get_event_loop()
data = ioloop.run_until_complete(run(urls))
print(data)
ioloop.close()
>>> l = [{'name': 'C', 'price': 5}, {'name': 'A', 'price': 2}, {'name': 'B', 'price': 1}]
>>> newlist = sorted(l, key=lambda k: k['price'])
>>> newlist
[{'name': 'B', 'price': 1}, {'name': 'A', 'price': 2}, {'name': 'C', 'price': 5}]
>>> from operator import itemgetter
>>> newlist = sorted(l, key=itemgetter('price'))
>>> newlist
[{'name': 'B', 'price': 1}, {'name': 'A', 'price': 2}, {'name': 'C', 'price': 5}]
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 9090)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
sock.listen(1)
while True:
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
while True:
data = connection.recv(1024)
print('received {!r}'.format(data))
if data:
print('sending data back to the client')
input_data = (data.decode())
expression = input_data[0] + input_data[2] + input_data[1]
result = eval(expression)
connection.sendall(str(result).encode())
else:
print('no data from', client_address)
break
finally:
connection.close()
import socket
sock = socket.socket()
sock.connect(('localhost', 9090))
a = input("a= ")
b = input("b= ")
do = input("+ - / * ")
message = a + b + do
sock.send(message.encode())
data = sock.recv(1024)
res = data.decode()
print(res)
sock.close()